package top.cardone.beans;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import top.cardone.context.ApplicationContextHolder;

import java.util.LinkedHashMap;

/**
 * Created by Administrator on 2015/5/22.
 */
public class JsonStringFactoryBean implements FactoryBean<Object>,
        ApplicationContextAware {
    @lombok.Setter
    private ApplicationContext applicationContext;
    @lombok.Setter
    private String jsonString;
    @lombok.Setter
    @lombok.Getter
    private Class<?> objectType;
    @lombok.Setter
    @lombok.Getter
    private boolean singleton;

    private Object singletonObject;

    @Override
    public Object getObject() throws Exception {
        if (StringUtils.isBlank(jsonString)) {
            return null;
        }

        if (BooleanUtils.isTrue(singleton) && singletonObject != null) {
            return singletonObject;
        }

        if (objectType == null) {
            singletonObject = ApplicationContextHolder.func(Gson.class, gson -> gson.fromJson(jsonString, new TypeToken<LinkedHashMap<String, Object>>() {
            }.getType()));
        } else {
            singletonObject = ApplicationContextHolder.func(Gson.class, gson -> gson.fromJson(jsonString, objectType));
        }

        return singletonObject;
    }
}
